package com.newcoder.community.serverce;

import com.newcoder.community.dao.LoginTicketMapper;
import com.newcoder.community.dao.UserMapper;
import com.newcoder.community.pojo.LoginTicket;
import com.newcoder.community.pojo.User;
import com.newcoder.community.utill.CommunityUtill;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginTicketServiceImpl implements LoginTicketService{
    @Autowired
    private LoginTicketMapper loginTicketMapper;
    @Autowired
    private UserMapper userMapper;
    public int insertTicket(LoginTicket loginTicket){
        return loginTicketMapper.insertTicket(loginTicket);
    }
    public LoginTicket selectByTicket(String ticket){
        return loginTicketMapper.selectByTicket(ticket);
    }
    public int updateStatus(String ticket,int status){
        return loginTicketMapper.updateStatus(ticket,status);
    }
    public Map<String, String> login(String username, String password, int expiredSeconds) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在");
            return map;
        }
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活");
            return map;
        }

        if (!user.getPassword().equals((CommunityUtill.md5(password)) + user.getSalt())) {
            map.put("passwordMsg", "密码不正确");
            return map;
        }
        LoginTicket loginTicket=new LoginTicket(user.getId(),CommunityUtill.generateUUID(),0);
        loginTicket.setExpired(new Date(System.currentTimeMillis()+ expiredSeconds*1000));
        this.insertTicket(loginTicket);
        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    public void logOut(String ticket){
        loginTicketMapper.updateStatus(ticket,1);

    }
}
